# This script will create a stacked bar graph for the proportion statistics broken 
# down by user tenure and offset year.
#
# Usage:
#
#         Rscript tenureOffsetProportion.R [inputfile] [outputdir] [outputname] [current]
#
# Where [inputfile] is the name of the stats file to graph
# 
# Where [outputdir] is the name of a directory to write the graph files to
#
# Where [outputname] is the base name to use for saving graph files
#
# Where [current] is TRUE or FALSE, indicating whether to add the current users label
#
# The plot will have a legend with colors filled in by rainbow(), so it should have 
# the same colors as the other graphs for created for that cluster model 
# assuming that rainbow() is deterministic with respect to input size.

args <- commandArgs(TRUE)

inputfile <- args[1]
outputdir <- args[2]
outputname <- args[3]
current <- as.logical(args[4])

data <- as.matrix(read.table(file=inputfile, sep="\t", quote="", comment.char=""))

# Break the stats up by their tenure
start <- 1
startval <- 0
blocks <- list()
for(i in 1:nrow(data)) {
  if (as.integer(data[i, 1]) != startval) {
    blocks[[length(blocks)+1]] <- matrix(data = data[start:(i-1), ], nrow = (i - start), ncol = ncol(data))
    start <- i
    startval <- as.integer(data[i, 1])
  }
}

blocks[[length(blocks)+1]] <- matrix(data = data[start:nrow(data), ], nrow = (nrow(data)-start+1), ncol=ncol(data))

# Make a plot and legend for each data block
# Start at tenure 1 because R absolutely fucking refuses to do tenure 0 correctly
for(i in 2:length(blocks)) {
  block <- blocks[[i]]
  
  tenure <- as.character(block[1, 1])
  xnames <- as.character(block[, 2])
  proportions <- t(block[, -1:-2])
  numclusters <- nrow(proportions)

  xlabel <- "Offset Year"
  ylabel <- "Archetype Proportion"
  
  clusterlabels <- as.character(c(1:numclusters))
  
  if (current == FALSE) {
    title <- paste("Archetype Unsurvived User Proportion by Offset Year for Tenure", tenure)
  } else {
    title <- paste("Archetype Current User Proportion by Offset Year for Tenure", tenure)
  }
  
  graphoutput <- paste(outputdir, outputname, tenure, "_plot.png", sep="")
  legendoutput <- paste(outputdir, outputname, tenure, "_legend.png", sep="")
  
  colors <- rainbow(numclusters)
  
  png(graphoutput, width=500, height=500)
  
  barplot(proportions, main=title, ylab=ylabel, xlab=xlabel, names.arg=xnames, col=colors)
  
  dev.off()
  
  png(legendoutput)
  
  plot.new()
  
  legend("topleft", legend=clusterlabels, fill=colors)
  
  dev.off()
}
